package controller

import (
	"time"

	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/project/star/star/model"
	"gddgame.cc/galaxy/utils/def"
	"gddgame.cc/galaxy/utils/orm"
)

func VerifyItems(context def.Context, items map[int]int, userId int) error {
	//if items == nil || len(items) == 0 {
	//	return nil
	//}
	//var uItems []model.UserItem
	//var itemIds []int
	//var itemMap map[int]*model.UserItem
	//count, err := model.UserItemModel.Query().Where("=", "user_id", userId).Count()
	//if err != nil {
	//	return SystemExceptionDetail("获取用户道具失败", err)
	//}
	//
	//itemIds = make([]int, 0, len(items))
	//for key, _ := range items {
	//	itemIds = append(itemIds, key)
	//}
	//if _, err = model.UserItemModel.Query().Where("=", "user_id", userId).Where("in", "item_id", itemIds).Find(&uItems); err != nil {
	//	return SystemExceptionDetail("获取用户道具失败", err)
	//}
	//if len(uItems) > 0 {
	//	itemMap = make(map[int]*model.UserItem, len(uItems))
	//	for _, item := range uItems {
	//		itemMap[item.ItemId] = &item
	//	}
	//} else {
	//	itemMap = map[int]*model.UserItem{}
	//}
	//
	//for key, number := range items {
	//	item := center.Items[key]
	//	uItem, ok := itemMap[key]
	//	if ok {
	//		if number+uItem.Number > item.Max {
	//			count += 1
	//		}
	//	} else {
	//		count += 1
	//	}
	//}
	//if int(count) > maxItems {
	//	return ValidException("STORE_MAX")
	//}
	return nil
}

func AddItems(context def.Context, items map[int]int, user *model.User) error {
	if items == nil || len(items) == 0 {
		return nil
	}
	var err error
	var uItems []model.UserItem
	var itemIds []int
	var itemMap map[int]*model.UserItem
	// 添加获取的道具
	if len(items) == 0 {
		return nil
	}
	itemIds = make([]int, 0, len(items))
	for key, _ := range items {
		itemIds = append(itemIds, key)
	}
	if _, err = model.UserItemModel.Query().Where("=", "user_id", user.Id).Where("in", "item_id", itemIds).Find(&uItems); err != nil {
		return SystemExceptionDetail("查找用户道具失败", err)
	}
	if len(uItems) > 0 {
		itemMap = make(map[int]*model.UserItem, len(uItems))
		for _, item := range uItems {
			itemMap[item.ItemId] = &item
		}
	} else {
		itemMap = map[int]*model.UserItem{}
	}

	for key, number := range items {
		if number <= 0 {
			continue
		}
		item := Center.Items[key]
		uItem, ok := itemMap[key]
		if ok {
			// 设定无限大，用于限制武器等一个堆叠
			if item.Max > 0 && number+uItem.Number > item.Max {
				uItems = append(uItems, model.UserItem{
					Id:         uItem.Id,
					UserId:     user.Id,
					ItemId:     item.Id,
					Number:     item.Max,
					Durability: 100,
				})
				// 超过最大堆叠
				number = number - (item.Max - uItem.Number)
				uItem.Number = item.Max
				uItems = append(uItems, model.UserItem{
					Id:         0,
					UserId:     user.Id,
					ItemId:     item.Id,
					Number:     number,
					Durability: 100,
				})
			} else {
				uItems = append(uItems, model.UserItem{
					Id:         uItem.Id,
					UserId:     user.Id,
					ItemId:     item.Id,
					Number:     number + uItem.Number,
					Durability: 100,
				})
			}
		} else {
			uItems = append(uItems, model.UserItem{
				Id:         0,
				UserId:     user.Id,
				ItemId:     item.Id,
				Number:     number,
				Durability: 100,
			})
		}
	}
	for _, item := range uItems {
		insert := false
		if item.Id == 0 {
			insert = true
		}
		if _, err = model.UserItemModel.Query().Save(insert, &item); err != nil {
			return SystemExceptionDetail("添加道具失败", err)
		}

	}
	return nil
}

func GetItems(context def.Context, userId int, language string, updateTime *time.Time) ([]*model.UserItemExt, error) {
	var err error
	var uItems []model.UserItem
	query := model.UserItemModel.Query().Where("=", "user_id", userId)
	if updateTime != nil && updateTime.After(*Center.LastItemUpdateTime) {
		query.Where(">", "update_time", updateTime)
	}
	if _, err = query.Find(&uItems); err != nil {
		return nil, SystemExceptionDetail("查找用户道具失败", err)
	}
	// 获取道具信息
	items := make([]*model.UserItemExt, len(uItems))
	for key := range uItems {
		// 多语言选项
		tmp := Center.GetItem()[uItems[key].ItemId]
		items[key] = model.NewUserItem(&uItems[key], tmp)
	}
	return items, nil
}

func BuyItem(context def.Context, area string, shopItemId int, user *model.User, info map[int]int) error {
	shopItem := Center.ShopItems[shopItemId]
	item := Center.Items[shopItem.ItemId]
	var money int
	var key string
	switch item.CoinType {
	case model.GoldCoin:
		money = user.Gold
		key = "gold"
		// 是否有钱买
		if money < shopItem.BuyPrice {
			return ValidException("GOLD_NOENOUGH")
		}
	case model.DiamondCoin:
		money = user.Diamond
		key = "diamond"
		// 是否有钱买
		if money < shopItem.BuyPrice {
			return ValidException("DIAMOND_NOENOUGH")
		}
	}
	info[item.Id] = shopItem.Number
	data := map[string]interface{}{
		key: &orm.UpdateOperate{Operate: "-", Value: shopItem.BuyPrice},
	}
	if err := Center.UpdateUser(user, data); err != nil {
		return err
	}

	return nil
}

func SellItem(context def.Context, userItemId int, number int, user *model.User) error {
	var item model.UserItem
	if userItemId == 0 {
		return EmptyException("ITEM_EMPTY")
	}
	if ok, err := model.UserItemModel.Query().Where("=", "user_id", user.Id).Where("=", "id", userItemId).One(&item); !ok {
		return SystemExceptionDetail("查找用户道具失败", err)
	}
	if item.Number < number {
		return ValidException("ITEM_NOENOUGH")
	}
	settingItem := Center.Items[item.ItemId]
	price := settingItem.SellPrice * number
	// 按损耗卖
	if item.Durability != 100 {
		price = price * item.Durability / 100
	}
	var key string
	switch settingItem.CoinType {
	case model.GoldCoin:
		key = "gold"
	case model.DiamondCoin:
		key = "diamond"
	}
	data := map[string]interface{}{
		key: &orm.UpdateOperate{Operate: "+", Value: price},
	}
	if settingItem.CoinType == model.GoldCoin {
		if err := Center.UpdateStatSingle(context, user, Center.StatData, model.GoldStat, int32(price), false); err != nil {
			return err
		}
		if err := UpdateBadgeSingle(context, user, model.GoldBadge, data); err != nil {
			return err
		}
	}
	if err := Center.UpdateUser(user, data); err != nil {
		return err
	}
	if number == item.Number {
		if _, err := model.UserItemModel.PK(userItemId).Delete(); err != nil {
			return SystemExceptionDetail("删除用户道具失败", err)
		}
	} else {
		if _, err := model.UserItemModel.PK(userItemId).Update(map[string]interface{}{
			"number": &orm.UpdateOperate{Operate: "-", Value: number},
		}); err != nil {
			return SystemExceptionDetail("减少用户道具失败", err)
		}
	}
	return nil
}

func RepairItem(context def.Context, userItemId int, user *model.User) error {
	if userItemId == 0 {
		return EmptyException("ITEM_EMPTY")
	}
	var item model.UserItem
	if ok, err := model.UserItemModel.Query().Where("=", "user_id", user.Id).Where("=", "id", userItemId).One(&item); !ok {
		return SystemExceptionDetail("查找用户道具失败", err)
	}
	if item.Durability == 100 {
		return nil
	}
	settingItem := Center.Items[item.ItemId]
	price := settingItem.SellPrice * (100 - item.Durability) / 100

	var money int
	var key string
	switch settingItem.CoinType {
	case model.GoldCoin:
		money = user.Gold
		key = "gold"
		// 是否有钱买
		if money < price {
			return ValidException("GOLD_NOENOUGH")
		}
	case model.DiamondCoin:
		money = user.Diamond
		key = "diamond"
		if money < price {
			return ValidException("DIAMOND_NOENOUGH")
		}
	}
	data := map[string]interface{}{
		key: &orm.UpdateOperate{Operate: "-", Value: price},
	}

	if err := Center.UpdateUser(user, data); err != nil {
		return err
	}
	if _, err := model.UserItemModel.PK(userItemId).Update(map[string]interface{}{
		"durability": 100,
	}); err != nil {
		return SystemExceptionDetail("修复用户道具失败", err)
	}
	return nil
}
